package snippet.jms;

import java.util.Properties;

import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;


public class HelloQueueSender
{

	static final String providerContextFactoryTIBCO = "com.tibco.tibjms.naming.TibjmsInitialContextFactory";

	static final String providerURLTIBCO = "tibjmsnaming://localhost:7222";

	static final String providerContextFactoryActiveMQ = "org.apache.activemq.jndi.ActiveMQInitialContextFactory";

	static final String providerURLActiveMQ = "tcp://localhost:61696";

	public static void main(final String[] args)
	{
		try
		{
			// Locate the JNDI naming service
			final Context ctx = getInitialContext();

			// Locate the Queue Connection Factory via JNDI
			final QueueConnectionFactory factory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory");

			// Create a new Queue Connection
			final QueueConnection conn = factory.createQueueConnection();

			// Create a Queue Session, ask JMS to acknowledge the messages
			// The session is non-transactional; you don't send messages
			// as part of a transaction.
			final QueueSession session = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

			Queue queue = null;

			try
			{
				// See if someone has already created the queue
				//queue = (Queue) ctx.lookup("helloQueue");
				queue = session.createQueue("helloQueue");
			}
			catch (final Exception exc)
			{
				System.out.println("Queue not created");
				// If not, create a new Queue and store it in the JNDI directory
				/*
				 * queue = session.createQueue("helloQueue"); ctx.bind("helloQueue", queue);
				 */}

			// Create a simple text message
			final TextMessage message = session.createTextMessage("Hello 76");

			// Create a QueueSender (so you can send messages)
			final QueueSender sender = session.createSender(queue);

			// Tell the Queue Connection you are ready to interact with the message service
			conn.start();

			/*
			 * for (;;) {
			 */
			// Send a message
			sender.send(message);

			// Wait 5 seconds (5,000 milliseconds) before sending another message
			//try { Thread.sleep(5000); } catch (Exception ignore) {}
			/* } */
			conn.close();
		}
		catch (final Exception exc)
		{
			exc.printStackTrace();
		}
		System.out.println(" Sent message");

	}

	private static InitialContext getInitialContext() throws NamingException
	{
		final Properties prop = new Properties();
		prop.put("java.naming.factory.initial", providerContextFactoryTIBCO);
		prop.put("java.naming.provider.url", providerURLTIBCO); //tcp://localhost:61616
		//prop.put("queue.helloQueue", "helloQueue");
		//prop.put("queue.sampleQueue", "sampleQueue");

		return new InitialContext(prop);
	}
}
